# -*- coding: cp1251 -*- 
import Player
class Game:
    
    def __init__( self , game_name , min_players ):
        self.game_name = game_name
        self.sessions = {}
        self.players  = {}
        self.min_players  = min_players
        self.game_state = 'not started'
        
    def __player_exists__( self , player_name  ):
        
        return self.players.has_key( player_name )
    
    def __session_exists__(self, session_id ):
        
        return self.sessions.has_key( session_id )
            
    def add_player( self , player_name , offered_session_id ):
        
        if( self.__player_exists__( player_name ) == True ):
            return -1
        
        if( self.__session_exists__( offered_session_id ) == True ):
            return -1
        
        p = Player.Player( player_name, offered_session_id )
        self.sessions[ offered_session_id ] = p
        self.players[ player_name ] = p
        return offered_session_id
    
    def remove_player( self , session_id ):
        
        player_name = self.sessions[ session_id ].player_name
        del self.sessions[ session_id ]
        del self.players[ player_name ]
            
    def enum_players( self ):
        
        players_str = ''
        for i in self.players.keys():
            players_str = players_str + i + ';'
            
        return players_str
    
    def get_player_by_session_id( self , session_id ):
        
        if( self.sessions.has_key( session_id ) ):
            return self.sessions[ session_id ]
        else:
            return None
    
    def get_player_by_name( self , player_name ):
        
        if( self.players.has_key( player_name ) ):
            return self.players[ player_name ]
        else:
            return None
            
    def check_players_ready( self ):
        
        ready = True 
        for i in self.sessions.keys():
            if( self.sessions[ i ].ready == False ):
                ready = False
                break
        
        return ready
    
    def start( self ):
        
        if( len( self.players ) >= self.min_players ):
            for i in self.sessions.keys():
                self.sessions[i].add_message( "server", "game started" )
                
            self.game_state = 'started'
            
    def check_winner( self ):
        
        dead = 0
        pl = self.players.values()
        for i in pl:
            if( i.is_alive() == False ):
                dead = dead + 1
                
        return len( pl ) - dead == 1
            
        
            
            